package com.qf.netty.handler;

import com.qf.netty.entity.Message;
import com.qf.netty.entity.Rooms;
import com.qf.netty.entity.User;
import com.qf.netty.handler.base.BaseMsgChannelHandler;
import com.qf.netty.utils.RoomUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.kurento.client.MediaPipeline;
import org.springframework.stereotype.Component;

/**
 * 主播方退出房间的处理器
 * author Ken
 * create_time 2023/1/5
 */
@Component
@ChannelHandler.Sharable
public class MasterOutMsgChannelHandler extends BaseMsgChannelHandler {
    @Override
    protected int action() {
        return 9;
    }

    @Override
    protected void handler(ChannelHandlerContext ctx, Message msg) {
        //获取房间号
        Integer roomId = Integer.parseInt(msg.getMsg() + "");
        //找到房间对象
        Rooms rooms = RoomUtils.getRooms(roomId);

        if (rooms == null) return;

        //获取主播的MediaPipeline - 将管道上的所有端点全部释放
        MediaPipeline mediaPipeline = rooms.getMediaPipeline();
        mediaPipeline.release();

        //通知所有的消费者 主播已经退出
        for (User slave : rooms.getSlaves()) {
            Message message = new Message()
                    .setAction(10);
            slave.getChannel().writeAndFlush(message);
        }

        //将房间从列表中移除
        RoomUtils.removeRooms(roomId);
    }
}
